<template>
  <div class="preview-renderer" :style="{ width: `${canvasWidth}px`, height: `${canvasHeight}px` }">
    <template v-for="component in processedComponents" :key="component.id">
      <div 
        :style="getComponentStyle(component)" 
        class="preview-component"
        :class="getComponentClasses(component)"
        @click="handleComponentClick(component, $event)"
      >
        <component 
          :is="resolveComponentType(component.type)" 
          v-bind="getComponentProps(component)"
          :isPreviewMode="true"
          :isExportMode="false"
        >
          <!-- 处理子组件的渲染 - 不再使用递归组件 -->
          <template v-if="hasChildren(component)">
            <div 
              v-for="child in component.children" 
              :key="child.id"
              :style="getComponentStyle(child)"
              class="preview-component"
              @click.stop="handleComponentClick(child, $event)"
            >
              <component 
                :is="resolveComponentType(child.type)" 
                v-bind="getComponentProps(child)"
                :isPreviewMode="true"
                :isExportMode="false"
              >
                <!-- 简化嵌套，最多支持两层嵌套 -->
                <template v-if="hasGrandchildren(child)">
                  <div 
                    v-for="grandchild in child.children" 
                    :key="grandchild.id"
                    :style="getComponentStyle(grandchild)"
                    class="preview-component"
                    @click.stop="handleComponentClick(grandchild, $event)"
                  >
                    <component 
                      :is="resolveComponentType(grandchild.type)" 
                      v-bind="getComponentProps(grandchild)"
                      :isPreviewMode="true"
                      :isExportMode="false"
                    >
                      {{ getComponentText(grandchild) }}
                    </component>
                  </div>
                </template>
                <template v-else>
                  {{ getComponentText(child) }}
                </template>
              </component>
            </div>
          </template>
          <template v-else>
            {{ getComponentText(component) }}
          </template>
        </component>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { defineProps, computed, ref, onMounted, watch, getCurrentInstance } from 'vue';
import { type CanvasComponent } from '@/stores/designStore';
import { ElMessage } from 'element-plus';
         
// 导入预览服务
import previewService from '@/services/PreviewService';
// 导入组件管理服务
import componentManager from '@/services/ComponentManagerService';

const props = defineProps({
  components: {
    type: Array as () => CanvasComponent[],
    required: true
  },
  canvasWidth: {
    type: Number,
    default: 800
  },
  canvasHeight: {
    type: Number,
    default: 600
  },
  parentComponent: {
    type: Object as () => CanvasComponent | null,
    default: null
  }
});

// 处理后的组件列表
const processedComponents = ref<CanvasComponent[]>([]);

// 在组件挂载和props变化时处理组件
onMounted(async () => {
  await prepareComponents();
  
  // 初始化组件管理器，传入应用上下文
  const appContext = getCurrentInstance()?.appContext;
  if (appContext?.app?._context?.components) {
    componentManager.initializeComponents(appContext.app._context.components);
  }
});

watch(() => props.components, async () => {
  await prepareComponents();
}, { deep: true });

// 使用预览服务处理组件
async function prepareComponents() {
  try {
    processedComponents.value = await previewService.prepareComponentTreeForPreview(props.components);
  } catch (error) {
    console.error('[PreviewRenderer] 处理组件出错:', error);
    ElMessage.error('预览处理出错');
    processedComponents.value = JSON.parse(JSON.stringify(props.components));
  }
}

// 简化的组件类型解析函数
const resolveComponentType = (type: string) => {
  return componentManager.getComponentInstance(type);
};

// 获取组件样式
const getComponentStyle = (component: CanvasComponent) => {
  const { style = {} } = component;
  
  // 确保所有必要的样式属性
  return {
    position: style.position || 'absolute',
    left: style.left || '0px',
    top: style.top || '0px',
    width: style.width || 'auto',
    height: style.height || 'auto',
    ...style
  };
};

// 获取组件类
const getComponentClasses = (component: CanvasComponent) => {
  const classes = [];
  
  // 添加组件类型作为类名
  if (component.type) {
    classes.push(`preview-${component.type}`);
  }
  
  // 添加预览模式类
  classes.push('preview-mode');
  
  return classes;
};

// 检查组件是否有子组件
const hasChildren = (component: CanvasComponent) => {
  return component.children && component.children.length > 0;
};

// 检查组件是否有孙子组件
const hasGrandchildren = (component: CanvasComponent) => {
  return component.children && component.children.length > 0;
};

// 获取组件的文本内容
const getComponentText = (component: CanvasComponent) => {
  if (!component || !component.props) return '';
  
  const { props } = component;
  // 使用标准化的组件类型
  const type = componentManager.normalizeComponentType(component.type);
  
  // 根据组件类型获取文本
  switch (type) {
    case 'button':
      return props.buttonText || props.content || '';
    case 'tag':
      return props.content || '';
    case 'radio':
    case 'checkbox':
      return props.textContent || props.label || '';
    case 'span':
    case 'p':
    case 'h1':
    case 'h2':
    case 'h3':
      return props.textContent || props.content || '';
    default:
      return '';
  }
};

// 获取组件属性
const getComponentProps = (component: CanvasComponent) => {
  if (!component.props) return { isPreviewMode: true };
  
  // 基本属性 - 所有组件都添加预览模式标志
  const baseProps = {
    isPreviewMode: true,
    isExportMode: false
  };
  
  // 使用标准化的组件类型
  const type = componentManager.normalizeComponentType(component.type);
  
  // 使用组件类型确定如何处理props
  if (['button', 'input', 'select', 'table'].includes(type)) {
    // 准备datas对象，包含基础属性和组件特定属性
    const specificProps = {};
    
    // 根据组件类型添加特定默认值
    if (type === 'button') {
      specificProps['buttonText'] = component.props.buttonText || '按钮';
      specificProps['type'] = component.props.type || 'primary';
    }
    
    // 合并所有属性
    return {
      ...baseProps,
      datas: {
        ...component.props,
        ...specificProps
      }
    };
  }
  
  // 对于Element Plus组件，直接传递props并添加预览标志
  return {
    ...component.props,
    ...baseProps
  };
};

// 处理组件点击
async function handleComponentClick(component: CanvasComponent, event: MouseEvent) {
  try {
    // 使用预览服务处理交互
    const shouldBubble = await previewService.handlePreviewInteraction(component, event);
    
    // 如果不允许冒泡，阻止事件
    if (!shouldBubble) {
      event.stopPropagation();
    }
  } catch (error) {
    console.error('[PreviewRenderer] 处理组件交互出错:', error);
  }
}
</script>

<style scoped>
.preview-renderer {
  position: relative;
  background-color: #fff;
  overflow: auto;
}

.preview-component {
  position: absolute;
}

/* 预览模式下的组件样式调整 */
:deep(.el-button),
:deep(.el-input),
:deep(.el-select),
:deep(.el-checkbox),
:deep(.el-radio),
:deep(.el-switch),
:deep(.el-tag),
:deep(.el-table) {
  pointer-events: auto !important;
}

/* 表格在预览模式下的样式 */
:deep(.el-table) {
  width: 100%;
  height: 100%;
}

/* 预览模式样式 */
.preview-mode {
  cursor: pointer;
}
</style> 